package com.cx.base.view;


import android.content.Intent;
import android.util.Pair;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import com.cx.base.presenter.IPresenter;
import com.cx.base.view.fragment.IFragment;
import com.cx.base.view.load.ILoad;
import com.cx.base.view.load.LoadingController;
import com.cx.util.device.FragmentHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;

/**
 *
 */
public class BaseView {

    private CompositeDisposable mDisposable;
    private LoadingController mLoadingController;
    private List<IPresenter.Presenter<? extends IView>> mPresenters;


    public BaseView(ILoad.Loading loading) {
        mPresenters = new ArrayList<>();
        mDisposable = new CompositeDisposable();
        mLoadingController = new LoadingController(loading);
    }


    public void onStart() {
        for (IPresenter.Presenter<? extends IView> presenter : mPresenters)
            presenter.onStart();
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        for (IPresenter.Presenter<? extends IView> presenter : mPresenters)
            presenter.onActivityResult(requestCode, resultCode, data);
    }

    public void addPresenter(IPresenter.Presenter<? extends IView> presenter) {
        mPresenters.add(presenter);
    }

    public LoadingController getLoadingController() {
        return mLoadingController;
    }

    public CompositeDisposable getDisposable() {
        return mDisposable;
    }


    public void replaceFragment(IFragment fragment,
                                FragmentManager manager,
                                boolean addToBackStack,
                                Pair<View, String>... sharedElements) {
        FragmentHelper.replace(fragment.getRes(),
                fragment,
                manager,
                addToBackStack,
                sharedElements);
    }

    public void onDestroy() {
        for (IPresenter.Presenter<? extends IView> presenter : mPresenters) {
            presenter.onDestroy();
        }
        mPresenters.clear();
        mDisposable.dispose();
        mLoadingController.onDestroy();
        mPresenters = null;
        mDisposable = null;
    }
}
